<template>
  <div class="document-manager">
    <div class="page-header">
      <h1 style="display: inline-block">文档管理</h1>

      <el-button @click="openDrawer" style="float: right; border-radius: 50%; margin-top: 30px;margin-right: 30px;width: 50px;height: 50px">
        <el-icon size="20" style="color: #6aaff6;"><ArrowLeftBold /></el-icon>
      </el-button>
    </div>

    <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <el-card class="stats-card">
          <template #header>
            <div class="card-header">
              <span>文档统计</span>
              <el-button
                  type="primary"
                  link
                  @click="loadStats"
                  :loading="statsLoading"
              >
                <el-icon><refresh /></el-icon>
              </el-button>
            </div>
          </template>
          <el-row :gutter="20">

            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-label">总实体数</div>
                <div class="stat-value">{{ stats.totalEntities || 0 }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-label">总关系数</div>
                <div class="stat-value">{{ stats.totalRelationships || 0 }}</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <el-card class="upload-section">
          <template #header>
            <div class="card-header">
              <span>文档上传</span>
            </div>
            <el-select-v2
                v-model="promptText"
                :options="categories"
                placeholder="选择知识抽取的类型"
                size="large"
                style="width: 240px; margin-top: 10px;"
            />
          </template>

          <el-upload
              class="upload-area"
              drag
              :action="`${axios.defaults.baseURL}/api/upload`"
              :headers="uploadHeaders"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :on-progress="handleUploadProgress"
              :multiple="false"
              :auto-upload="true"
              :show-file-list="true"
              :limit="1"
              name="file"
              :data="{ prompt: promptText }">
            <template #trigger>
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                拖拽文件到此处或 <em>点击上传</em>
              </div>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                支持 PDF、Word 格式文档，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </el-card>
      </el-col>
    </el-row>

    <el-drawer
        v-model="drawer"
        title="我的文档"
        direction="rtl"
        :before-close="closeDrawer"
    >
      <h1>文档展示</h1>
      <div class="file-list">
        <el-card
            v-for="file in fileList"
            :key="file.id"
            class="file-card"
            shadow="hover"
        >
          <div class="file-content">
            <!-- 左侧：文件图标 -->
            <img
                v-if="getFileExtension(file.filename) === 'pdf' "
                src="@/assets/pdf.png"
                alt="File Icon"
                class="file-icon"
            />
            <img
                v-else
                src="@/assets/word.png"
                alt="File Icon"
                class="file-icon"
            />
            <!-- 右侧：文件名和操作按钮 -->
            <div class="file-info">
              <span class="filename">{{ file.filename }}</span>
              <div class="actions">
                <el-icon @click="downloadDocument(file.filename)" size="20" style="color: #6aaff6;margin-right: 30px;"><Download /></el-icon>
                <el-icon @click="deleteFile(file.filename)" size="20" style="color: red"><Delete /></el-icon>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import axios from 'axios'
import request from '@/utils/request'

import {
  UploadFilled,
  Search,
  Refresh
} from '@element-plus/icons-vue'

// 响应式数据
const documents = ref([])
const stats = ref({
  totalDocuments: 0,
  todayDocuments: 0,
  totalEntities: 0,
  totalRelationships: 0,
  documentTypes: {}
})
const loading = ref(false)
const statsLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const recentActivities = ref([])

//用户提示词
const promptText = ref('人文');
//知识分类
const category = ref('人文')
const categories = ref([
  {
    value: '生活',
    label: '生活',
  },
  {
    value: '人文',
    label: '人文',
  },
  {
    value: '军事',
    label: '军事',
  },
  {
    value: '科技',
    label: '科技',
  }
])
// 上传配置
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${localStorage.getItem('token')}`,
  'X-Requested-With': 'XMLHttpRequest'
}))

// 处理上传进度
const handleUploadProgress = (event, file) => {
  if (event.percent) {
    ElMessage.info({
      message: `正在上传: ${file.name} (${Math.round(event.percent)}%)`,
      duration: 1000
    })
  }
}

// 上传前检查
const beforeUpload = (file) => {
  // 检查是否已登录
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.error('请先登录')
    return false
  }

  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }

  const allowedTypes = {
    'application/pdf': 'PDF',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'DOCX'
  }

  if (!allowedTypes[file.type]) {
    ElMessage.error(`不支持的文件类型: ${file.type}。只支持 PDF 和 Word 文档!`)
    return false
  }

  // 显示上传开始的消息
  ElMessage.info(`开始上传文件: ${file.name}`)
  return true
}

// 上传成功处理
const handleUploadSuccess = async (response, uploadFile) => {
  ElMessage.success('文档上传成功')
  await Promise.all([
    loadDocuments(),
    loadStats(),
    loadActivities()
  ])
}

// 上传错误处理
const handleUploadError = (error, file) => {
  let errorMessage = '上传失败'
  if (error.response && error.response.data) {
    errorMessage = error.response.data.detail || error.response.data.message || error.message
  }
  ElMessage.error(`文档 "${file.name}" ${errorMessage}`)
}

// 加载文档列表
const loadDocuments = async () => {
  try {
    loading.value = true
    const response = await axios.get('/api/documents', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        search: searchQuery.value.trim()
      }
    })

    if (response.data) {
      documents.value = response.data.documents.map(doc => ({
        ...doc,
        size: formatFileSize(doc.size)
      }))
      total.value = response.data.total
    }
  } catch (error) {
    ElMessage.error('获取文档列表失败：' + (error.response?.data?.detail || error.message))
  } finally {
    loading.value = false
  }
}

// 加载统计信息
const loadStats = async () => {
  try {
    statsLoading.value = true
    const response = await axios.get('/api/stats')
    if (response.data.code === 200) {
      const data = response.data.data
      stats.value = {
        totalDocuments: data.totalDocuments || 0,
        totalEntities: data.totalNodes || 0,
        totalRelationships: data.totalRelationships || 0,
        documentTypes: data.documentTypes || {}
      }
      console.log('Stats updated:', stats.value)
    } else {
      ElMessage.error(response.data.message || '获取统计信息失败')
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
    ElMessage.error('获取统计信息失败: ' + (error.response?.data?.message || error.message))
  } finally {
    statsLoading.value = false
  }
}

// 文件大小格式化
const formatFileSize = (size) => {
  if (typeof size === 'string') return size
  const units = ['B', 'KB', 'MB', 'GB']
  let index = 0
  let fileSize = size

  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024
    index++
  }

  return `${fileSize.toFixed(2)} ${units[index]}`
}

// 查看文档
const viewDocument = (row) => {
  window.open(`${axios.defaults.baseURL}/api/documents/${row.name}`, '_blank')
}

// 删除文档
const deleteDocument = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除文档 "${row.name}" 吗？此操作不可恢复！`,
        '删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning',
          confirmButtonClass: 'el-button--danger'
        }
    )

    loading.value = true
    await axios.delete(`/api/documents/${row.name}`)
    ElMessage.success('文档删除成功')
    await Promise.all([
      loadDocuments(),
      loadStats(),
      loadActivities()
    ])
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除文档失败：' + (error.response?.data?.detail || error.message))
    }
  } finally {
    loading.value = false
  }
}

// 搜索处理（带防抖）
const handleSearch = debounce(() => {
  currentPage.value = 1
  loadDocuments()
}, 300)

// 防抖函数
function debounce(fn, delay) {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 加载活动记录
const loadActivities = async () => {
  try {
    const response = await axios.get('/api/activities')
    recentActivities.value = response.data
  } catch (error) {
    console.error('获取活动记录失败：', error)
  }
}
//引导开关
const open = ref(false)
const ref1 = ref()
const ref2 = ref()
const ref3 = ref()
const getFileExtension = (filename) => {
  return filename.split('.').pop()?.toLowerCase() || ''
}
//用户获取自己上传的文档列表
const fileList = ref([])
const getFileList = async() => {
  try {
    const { data } = await axios.get('/api/file/file-list',{
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    console.log('文件列表', data.data)
    fileList.value = data.data
  } catch (e) {
    await Promise.reject(e)
  }
}
const drawer = ref(false)
const openDrawer = () => {
  drawer.value = true
}
const closeDrawer= () => {
  drawer.value = false
}
// 删除已上传文档
const deleteFile = async(name) => {
  try {
    const { data } = await axios.delete(`/api/documents/${name}`)
    console.log('删除文档信息：',data)
    await getFileList()
    ElMessage({
      message: data.message,
      type: 'warning',
    });
  } catch (e) {
    await Promise.reject(e)
  }
};
// 下载文档
const downloadDocument = async (name) => {
  ElMessage.info(`下载文档: ${name}`);
  try {
    // 使用 axios 下载文件，设置 responseType 为 'blob'
    const response = await axios.get(`/api/documents/download/${name}`, {
      responseType: 'blob'  // 告诉 axios 返回 Blob 对象
    });

    // response.data 是一个 Blob 对象
    const blob = response.data;
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = name; // 设置下载文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success(`正在下载: ${name}`);
  } catch (error) {
    ElMessage.error(`下载失败: ${name}`);
    console.error(error);
  }
};
// 组件挂载时加载数据
onMounted(async() => {
  await loadDocuments()
  await loadStats()
  await loadActivities()
  await getFileList()
})
</script>

<style scoped>
.document-manager {
  padding: 40px;
  margin: 0 auto;
  background: linear-gradient(135deg, #409EFF 0%, #36D1DC 100%);
  margin: 0;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.page-header {
  margin-bottom: 40px;
  margin-top: 20px;
  flex-shrink: 0;
  text-align: left;
  color: white;
}

.page-header h1 {
  font-size: 36px;
  font-weight: 600;
  margin-bottom: 16px;
  color: white;
}

.subtitle {
  color: #666;
  font-size: 1.1em;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  font-size: 1.2em;
  color: #2c3e50;
  margin: 0;
}

.upload-section {
  margin-bottom: 30px;
}

.upload-area {
  width: 100%;
  margin-bottom: 20px;
}

.search-input {
  width: 200px;
  margin-left: 20px;
}

.document-list {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.stats-card {
  margin-bottom: 30px;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.type-distribution {
  margin-top: 20px;
}

.type-item {
  margin-bottom: 15px;
}

.type-name {
  display: inline-block;
  width: 60px;
  color: #666;
}

.recent-activity {
  margin-top: 30px;
}

.el-timeline {
  padding: 0;
  margin-top: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.mb-4 {
  margin-bottom: 16px;
}

@media (max-width: 768px) {
  .document-manager {
    padding: 20px;
  }

  .search-input {
    width: 100%;
    margin-top: 10px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .card-header h2 {
    margin-bottom: 10px;
  }
}
.file-list {
  padding: 0 20px;
}

.file-card {
  margin-bottom: 10px;
}

.file-content {
  display: flex;
  align-items: center;
}

.file-icon {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.file-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filename {
  font-size: 16px;
}

.actions {
  display: flex;
  gap: 10px;
}
</style>